<template>
  <div class="user-list-container">
    <!-- 查询表单 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="搜索" prop="search">
              <el-input placeholder="搜索活动名称" v-model="queryParams.search" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="活动分类" prop="activity_category_id">
              <el-select v-model="queryParams.activity_category_id" placeholder="请选择分类" clearable>
                <el-option v-for="item in categoryOptions" :key="item.activity_category_id"
                  :label="item.activity_category_name" :value="item.activity_category_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核状态" prop="activity_status">
              <el-select v-model="queryParams.activity_status" placeholder="请选择状态" clearable>
                <el-option v-for="item in statusup" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <div style="display: flex; margin-bottom: 20px">
        <el-button type="primary" @click="openAddDialog">创建活动</el-button>
      </div>
      <el-table v-loading="loading" class="table" :data="tableData" border style="width: 100%">
        <el-table-column prop="activity_id" label="ID" width="80" fixed />
        <el-table-column prop="activity_title" label="活动标题" width="150" />
        <el-table-column prop="activity_cover_path" label="封面图">
          <template #default="scope">
            <el-image v-if="scope.row.activity_cover_path" :src="scope.row.activity_cover_path"
              style="width: 60px; height: 60px" :preview-src-list="[scope.row.activity_cover_path]" hide-on-click-modal
              preview-teleported />
          </template>
        </el-table-column>
        <el-table-column prop="activity_category_name" label="分类名称" width="150" />
        <el-table-column prop="activity_status" label="活动状态" width="150">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.activity_status)">
              {{ getStatusText(scope.row.activity_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="user_id" label="创建人" width="150">
          <template #default="scope">
            {{ scope.row.user_id === 0 ? '管理后台' : '用户端' }}
          </template>
        </el-table-column>
        <el-table-column prop="nick_name" label="昵称" width="150">
          <template #default="scope">
            {{ scope.row.user_id === 0 ? '官方创建' : scope.row.nick_name }}
          </template>
        </el-table-column>
        <el-table-column prop="is_home" label="首页是否展示" width="150">
          <template #default="scope">
            {{ scope.row.is_home === 0 ? '否' : '是' }}
          </template>
        </el-table-column>
        <el-table-column prop="browse_number" label="浏览量" />
        <el-table-column prop="collect_number" label="收藏量" />
        <el-table-column prop="province_name" label="省名称" />
        <el-table-column prop="city_name" label="市名称" />
        <el-table-column prop="area_name" label="区名称" />
        <el-table-column prop="detailed_address" label="详细地址" width="200" />
        <el-table-column prop="activity_describe" label="活动描述" width="200" />
        <el-table-column prop="created_at" label="添加时间" width="200" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button link v-if="scope.row.user_id == 0" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link v-else @click="handleEdits(scope.row)">查看</el-button>
            <el-button link type="primary" @click="handleAudit(scope.row)"
              v-if="scope.row.activity_status === 0">审核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" />
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="活动审核" width="600px">
      <el-form :model="auditForm" ref="auditFormRef" label-width="100px">
        <el-form-item label="活动标题">
          <el-input v-model="auditForm.activity_title" disabled />
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTagType(auditForm.activity_status)">
            {{ getStatusText(auditForm.activity_status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="-1">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="拒绝原因" prop="reject_reason" v-if="auditForm.status === -1">
          <el-input v-model="auditForm.reject_reason" type="textarea" :rows="3" placeholder="请输入拒绝原因" maxlength="200"
            show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 活动编辑/创建对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'edit' ? '编辑活动' : '创建活动'" width="1000px"
      :before-close="handleCloseAddDialog">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="150px" class="demo-form">
        <el-form-item label="活动标题" prop="activity_title">
          <el-input v-model="form.activity_title" placeholder="请输入活动标题" />
        </el-form-item>

        <el-form-item label="活动分类" prop="activity_category_id">
          <el-select v-model="form.activity_category_id" placeholder="请选择分类" clearable style="width: 100%">
            <el-option v-for="item in categoryOptions" :key="item.activity_category_id"
              :label="item.activity_category_name" :value="item.activity_category_id" />
          </el-select>
        </el-form-item>

        <el-form-item label="封面图" prop="activity_cover_path">
          <upload :key="`cover-upload-${dialogVisible}`" :img-file="form.activity_cover_path" :limit="1"
            @change="(val) => { form.activity_cover_path = val }" />
          <div class="el-form-item-msg">建议尺寸：750*420px</div>
        </el-form-item>

        <el-form-item label="轮播图" prop="activity_banner_arr">
          <el-upload action="https://shalong.taiyanyue.top/api/common/OSSFileUpload" list-type="picture-card"
            :file-list="bannerFileList" :on-success="handleBannerSuccess" :on-remove="handleBannerRemove"
            :before-upload="beforeBannerUpload" :limit="5" multiple :on-exceed="handleBannerExceed">
            <el-icon>
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">最多上传5张，建议尺寸：750*420px</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="活动描述" prop="activity_describe">
          <el-input v-model="form.activity_describe" type="textarea" :rows="3" placeholder="请输入活动描述" />
        </el-form-item>

        <el-form-item label="省市区" prop="province_id">
          <el-row :gutter="10">
            <el-col :span="8">
              <select v-model="form.province_id" @change="handleProvinceChange" class="native-select">
                <option v-for="item in provinceOptions" :key="item.district_id" :value="item.district_id">
                  {{ item.district_name }}
                </option>
              </select>
            </el-col>
            <el-col :span="8">
              <select v-model="form.city_id" @change="handleCityChange" :disabled="!form.province_id"
                class="native-select">
                <option v-for="item in cityOptions" :key="item.district_id" :value="item.district_id">
                  {{ item.district_name }}
                </option>
              </select>
            </el-col>
            <el-col :span="8">
              <select v-model="form.area_id" :disabled="!form.city_id" class="native-select">
                <option v-for="item in areaOptions" :key="item.district_id" :value="item.district_id">
                  {{ item.district_name }}
                </option>
              </select>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="详细地址" prop="detailed_address">
          <el-input v-model="form.detailed_address" placeholder="请输入详细地址" />
        </el-form-item>

        <el-form-item label="首页显示" prop="is_home">
          <el-switch v-model="form.is_home" :active-value="1" :inactive-value="0" />
        </el-form-item>

        <!-- 活动日期和时间段 -->
        <div v-for="(dateItem, dateIndex) in form.activity_spec_arr" :key="dateIndex" class="date-section">
          <el-divider content-position="left">活动日期 {{ dateIndex + 1 }}</el-divider>

          <el-form-item :label="`活动日期 ${dateIndex + 1}`" :prop="`activity_spec_arr.${dateIndex}.activity_at`"
            :rules="{ required: true, message: '请选择活动日期', trigger: 'change' }">
            <el-date-picker v-model="dateItem.activity_at" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
            <el-button style="margin-left: 20px;" type="danger" icon="Delete" circle
              @click="removeDateSection(dateIndex)" v-if="dateIndex > 0" />
          </el-form-item>

          <div v-for="(timeItem, timeIndex) in dateItem.activity_spec_time_arr" :key="timeIndex"
            class="time-slot-section">
            <el-divider content-position="left">时间段 {{ timeIndex + 1 }}</el-divider>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="`开始时间 ${timeIndex + 1}`"
                  :prop="`activity_spec_arr.${dateIndex}.activity_spec_time_arr.${timeIndex}.activity_start_at`"
                  :rules="{ required: true, message: '请选择开始时间', trigger: 'change' }">
                  <el-time-picker v-model="timeItem.activity_start_at" placeholder="开始时间" value-format="HH:mm"
                    format="HH:mm" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="`结束时间 ${timeIndex + 1}`"
                  :prop="`activity_spec_arr.${dateIndex}.activity_spec_time_arr.${timeIndex}.activity_end_at`"
                  :rules="{ required: true, message: '请选择结束时间', trigger: 'change' }">
                  <el-time-picker v-model="timeItem.activity_end_at" placeholder="结束时间" value-format="HH:mm"
                    format="HH:mm" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="`价格 ${timeIndex + 1}`"
                  :prop="`activity_spec_arr.${dateIndex}.activity_spec_time_arr.${timeIndex}.activity_price`"
                  :rules="{ required: true, message: '请输入价格', trigger: 'blur' }">
                  <el-input-number v-model="timeItem.activity_price" :min="0" :precision="2" controls-position="right"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="`最大参与人数 ${timeIndex + 1}`"
                  :prop="`activity_spec_arr.${dateIndex}.activity_spec_time_arr.${timeIndex}.activity_people_number`"
                  :rules="{ required: true, message: '请输入最大参与人数', trigger: 'blur' }">
                  <el-input-number v-model="timeItem.activity_people_number" :min="1" controls-position="right"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="16" style="display: flex; align-items: flex-end;">
                <el-button type="danger" icon="Delete" circle @click="removeTimeSlot(dateIndex, timeIndex)"
                  v-if="timeIndex > 0" />
              </el-col>
            </el-row>
          </div>

          <el-button type="primary" @click="addTimeSlot(dateIndex)" style="margin-top: 10px;">添加时间段</el-button>
        </div>

        <el-button type="primary" @click="addDateSection" style="margin-top: 20px;">添加活动日期</el-button>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisibles" title="查看" width="1500px" :before-close="handleCloseAddDialogs">
      <div style="display: flex;">
        <el-form label-width="150px" style="margin-right: 20px;" class="demo-form">
          <div style="font-size: 20px;font-weight: 550;">修改前</div>
          <el-form-item label="活动标题">
            <div>{{ forms.activity_title }}</div>
          </el-form-item>

          <el-form-item label="活动分类">
            <div>{{ getCategoryName(forms.activity_category_id) }}</div>
          </el-form-item>

          <el-form-item label="封面图">
            <el-image v-if="forms.activity_cover_path" :src="forms.activity_cover_path" style="width: 60px; height: 60px"
              :preview-src-list="[forms.activity_cover_path]" hide-on-click-modal preview-teleported />
            <span v-else>无</span>
          </el-form-item>

          <el-form-item label="轮播图">
            <div v-if="forms.activity_banner_arr && forms.activity_banner_arr.length > 0">
              <el-image v-for="(img, index) in forms.activity_banner_arr" :key="index" :src="img"
                style="width: 60px; height: 60px; margin-right: 10px" :preview-src-list="[img]" hide-on-click-modal
                preview-teleported />
            </div>
            <span v-else>无</span>
          </el-form-item>

          <el-form-item label="活动描述">
            <div style="white-space: pre-line;">{{ forms.activity_describe || '无' }}</div>
          </el-form-item>

          <el-form-item label="省市区">
            <div>
              {{ getRegionText() || '未选择' }}
            </div>
          </el-form-item>

          <el-form-item label="详细地址">
            <div>{{ forms.detailed_address || '无' }}</div>
          </el-form-item>

          <el-form-item label="首页显示">
            <div>
              <el-tag :type="forms.is_home === 1 ? 'success' : 'info'">
                {{ forms.is_home === 1 ? '是' : '否' }}
              </el-tag>
            </div>
          </el-form-item>

          <!-- 活动日期和时间段 - 展示模式 -->
          <div v-for="(dateItem, dateIndex) in forms.activity_spec_arr" :key="dateIndex" class="date-section">
            <el-divider content-position="left">活动日期 {{ dateIndex + 1 }}</el-divider>
            <el-form-item label="活动日期">
              <div>{{ dateItem.activity_at || '未设置' }}</div>
            </el-form-item>

            <div v-for="(timeItem, timeIndex) in dateItem.activity_spec_time_arr" :key="timeIndex"
              class="time-slot-section">
              <el-divider content-position="left">时间段 {{ timeIndex + 1 }}</el-divider>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="开始时间">
                    <div>{{ timeItem.activity_start_at || '未设置' }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="结束时间">
                    <div>{{ timeItem.activity_end_at || '未设置' }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="价格">
                    <div>{{ timeItem.activity_price || '未设置' }}</div>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="最大参与人数">
                    <div>{{ timeItem.activity_people_number || '未设置' }}</div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form>
        <el-form label-width="150px" class="demo-form">
          <div style="font-size: 20px;font-weight: 550;">修改后</div>
          <el-form-item label="活动标题">
            <div>{{ form.activity_title }}</div>
          </el-form-item>

          <el-form-item label="活动分类">
            <div>{{ getCategoryName(form.activity_category_id) }}</div>
          </el-form-item>

          <el-form-item label="封面图">
            <el-image v-if="form.activity_cover_path" :src="form.activity_cover_path" style="width: 60px; height: 60px"
              :preview-src-list="[form.activity_cover_path]" hide-on-click-modal preview-teleported />
            <span v-else>无</span>
          </el-form-item>

          <el-form-item label="轮播图">
            <div v-if="form.activity_banner_arr && form.activity_banner_arr.length > 0">
              <el-image v-for="(img, index) in form.activity_banner_arr" :key="index" :src="img"
                style="width: 60px; height: 60px; margin-right: 10px" :preview-src-list="[img]" hide-on-click-modal
                preview-teleported />
            </div>
            <span v-else>无</span>
          </el-form-item>

          <el-form-item label="活动描述">
            <div style="white-space: pre-line;">{{ form.activity_describe || '无' }}</div>
          </el-form-item>

          <el-form-item label="省市区">
            <div>
            {{ form.province_name }}-{{ form.city_name }}-{{ form.area_name }}
            </div>
          </el-form-item>

          <el-form-item label="详细地址">
            <div>{{ form.detailed_address || '无' }}</div>
          </el-form-item>

          <el-form-item label="首页显示">
            <div>
              <el-tag :type="form.is_home === 1 ? 'success' : 'info'">
                {{ form.is_home === 1 ? '是' : '否' }}
              </el-tag>
            </div>
          </el-form-item>

          <!-- 活动日期和时间段 - 展示模式 -->
          <div v-for="(dateItem, dateIndex) in form.activity_spec_arr" :key="dateIndex" class="date-section">
            <el-divider content-position="left">活动日期 {{ dateIndex + 1 }}</el-divider>
            <el-form-item label="活动日期">
              <div>{{ dateItem.activity_at || '未设置' }}</div>
            </el-form-item>

            <div v-for="(timeItem, timeIndex) in dateItem.activity_spec_time_arr" :key="timeIndex"
              class="time-slot-section">
              <el-divider content-position="left">时间段 {{ timeIndex + 1 }}</el-divider>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="开始时间">
                    <div>{{ timeItem.activity_start_at || '未设置' }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="结束时间">
                    <div>{{ timeItem.activity_end_at || '未设置' }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="价格">
                    <div>{{ timeItem.activity_price || '未设置' }}</div>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="最大参与人数">
                    <div>{{ timeItem.activity_people_number || '未设置' }}</div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialogs">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import tableMixin from "@/mixins/tableMixin";
import api from "@/request/api.js";
import upload from "@/components/upload.vue";
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

export default {
  name: "ActivityList",
  mixins: [tableMixin],
  components: { upload, Plus },
  data() {
    return {
      queryParams: {
        search: '',
        activity_category_id: null,
        activity_status: -10
      },
      apimodel: "activityspjifen",
      apival: "orderList",
      categoryOptions: [],
      statusup: [
        { value: -10, label: "全部" },
        { value: 1, label: "通过" },
        { value: -1, label: "拒绝" },
        { value: 0, label: "待审核" }
      ],
      provinceOptions: [],
      cityOptions: [],
      areaOptions: [],
      dialogVisible: false,
      dialogVisibles: false,
      dialogType: "",
      form: {
        activity_title: "",
        activity_category_id: null,
        activity_cover_path: "",
        activity_banner_arr: [],
        activity_describe: "",
        province_id: null,
        city_id: null,
        area_id: null,
        detailed_address: "",
        is_home: 0,
        activity_spec_arr: [
          {
            activity_at: "",
            activity_spec_time_arr: [
              {
                activity_start_at: "",
                activity_end_at: "",
                activity_price: 0,
                activity_people_number: 1
              }
            ]
          }
        ]
      },
      forms: {
        activity_title: "",
        activity_category_id: null,
        activity_cover_path: "",
        activity_banner_arr: [],
        activity_describe: "",
        province_id: null,
        city_id: null,
        area_id: null,
        detailed_address: "",
        is_home: 0,
        activity_spec_arr: [
          {
            activity_at: "",
            activity_spec_time_arr: [
              {
                activity_start_at: "",
                activity_end_at: "",
                activity_price: 0,
                activity_people_number: 1
              }
            ]
          }
        ]
      },
      bannerFileList: [],
      regionText: "",
      rules: {
        activity_title: [
          { required: true, message: "请输入活动标题", trigger: "blur" }
        ],
        activity_category_id: [
          { required: true, message: "请选择活动分类", trigger: "change" }
        ],
        activity_cover_path: [
          { required: true, message: "请上传封面图", trigger: "change" }
        ],
        province_id: [
          { required: true, message: "请选择省份", trigger: "change" }
        ],
        city_id: [
          { required: true, message: "请选择城市", trigger: "change" }
        ],
        area_id: [
          { required: true, message: "请选择区县", trigger: "change" }
        ]
      },
      auditDialogVisible: false,
      auditForm: {
        activity_id: null,
        activity_title: "",
        activity_status: null,
        status: 1,
        reject_reason: ""
      },
      activity_id: ''
    };
  },
  mounted() {
    this.getCategoryList();
    this.fetchDistricts(0);
  },
  methods: {
    // 获取分类名称
    getCategoryName(categoryId) {
      if (!categoryId) return '未选择';
      const category = this.categoryOptions.find(item => item.activity_category_id === categoryId);
      return category ? category.activity_category_name : '未知分类';
    },

    // 获取地区文本
    getRegionText() {
      if (!this.form.province_id) return '';

      const province = this.provinceOptions.find(item => item.district_id === this.form.province_id);
      const city = this.cityOptions.find(item => item.district_id === this.form.city_id);
      const area = this.areaOptions.find(item => item.district_id === this.form.area_id);

      return `${province?.district_name || ''} ${city?.district_name || ''} ${area?.district_name || ''}`.trim();
    },
    async getCategoryList() {
      try {
        const res = await api.activityspjifen.getList({ size: 999 });
        if (res.data.code == 200) {
          this.categoryOptions = res.data.content.data;
        }
      } catch (error) {
        console.error('获取分类列表失败:', error);
      }
    },

    async fetchDistricts(parentId) {
      try {
        const res = await api.activityspjifen.getDistricts({ parent_id: parentId });
        if (res.data.code == 200) {
          if (parentId === 0) {
            this.provinceOptions = res.data.content.data;
          } else {
            return res.data.content.data;
          }
        }
        return [];
      } catch (error) {
        console.error('获取地区数据失败:', error);
        return [];
      }
    },

    getStatusText(status) {
      const statusMap = {
        '0': '待审核',
        '1': '通过',
        '-1': '拒绝'
      };
      return statusMap[status] || '未知状态';
    },

    getStatusTagType(status) {
      const tagTypeMap = {
        '0': 'warning',
        '1': 'success',
        '-1': 'danger'
      };
      return tagTypeMap[status] || 'info';
    },

    async handleProvinceChange(event) {
      this.form.city_id = null;
      this.form.area_id = null;
      this.areaOptions = [];
      this.regionText = "";
      const val = event.target ? event.target.value : event;

      if (val) {
        this.cityOptions = await this.fetchDistricts(val);
        console.log(this.cityOptions)
      } else {
        this.cityOptions = [];
      }
      this.updateRegionText();
    },

    async handleCityChange(event) {
      this.form.area_id = null;
      this.regionText = "";
      const val = event.target ? event.target.value : event;
      if (val) {
        this.areaOptions = await this.fetchDistricts(val);
      } else {
        this.areaOptions = [];
      }
      this.updateRegionText();
    },

    updateRegionText() {
      if (this.form.province_id && this.form.city_id && this.form.area_id) {
        const province = this.provinceOptions.find(item => item.district_id === this.form.province_id);
        const city = this.cityOptions.find(item => item.district_id === this.form.city_id);
        const area = this.areaOptions.find(item => item.district_id === this.form.area_id);

        if (province && city && area) {
          this.regionText = `${province.district_name} ${city.district_name} ${area.district_name}`;
        }
      }
    },

    addDateSection() {
      this.form.activity_spec_arr.push({
        activity_at: "",
        activity_spec_time_arr: [
          {
            activity_start_at: "",
            activity_end_at: "",
            activity_price: 0,
            activity_people_number: 1
          }
        ]
      });
    },

    removeDateSection(index) {
      if (this.form.activity_spec_arr.length > 1) {
        this.form.activity_spec_arr.splice(index, 1);
      } else {
        ElMessage.warning('至少保留一个活动日期');
      }
    },

    addTimeSlot(dateIndex) {
      this.form.activity_spec_arr[dateIndex].activity_spec_time_arr.push({
        activity_start_at: "",
        activity_end_at: "",
        activity_price: 0,
        activity_people_number: 1
      });
    },

    removeTimeSlot(dateIndex, timeIndex) {
      const timeArr = this.form.activity_spec_arr[dateIndex].activity_spec_time_arr;
      if (timeArr.length > 1) {
        timeArr.splice(timeIndex, 1);
      } else {
        ElMessage.warning('至少保留一个时间段');
      }
    },

    handleBannerSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.form.activity_banner_arr.push(response.content.path);
        this.bannerFileList = fileList.map(item => {
          if (item.response) {
            return { url: item.response.content.path };
          }
          return item;
        });
      } else {
        ElMessage.error('上传失败: ' + (response.message || '未知错误'));
      }
    },

    handleBannerRemove(file, fileList) {
      const url = file.url || (file.response && file.response.content.path);
      if (url) {
        this.form.activity_banner_arr = this.form.activity_banner_arr.filter(item => item !== url);
      }
      this.bannerFileList = fileList;
    },

    handleBannerExceed(files, fileList) {
      ElMessage.warning(`最多只能上传5张轮播图，当前选择了${files.length}张，共${files.length + fileList.length}张`);
    },

    openAddDialog() {
      this.dialogVisible = true;
      this.dialogType = "add";
      this.resetForm();
      this.form = {
        activity_title: "",
        activity_category_id: null,
        activity_cover_path: "",
        activity_banner_arr: [],
        activity_describe: "",
        province_id: null,
        city_id: null,
        area_id: null,
        detailed_address: "",
        is_home: 0,
        activity_spec_arr: [
          {
            activity_at: "",
            activity_spec_time_arr: [
              {
                activity_start_at: "",
                activity_end_at: "",
                activity_price: 0,
                activity_people_number: 1
              }
            ]
          }
        ]
      };
      this.bannerFileList = [];
      this.regionText = "";
      this.cityOptions = [];
      this.areaOptions = [];
    },

    async handleEdit(row) {
      try {
        this.activity_id = row.activity_id;
        const res = await api.activityspjifen.getActivityDetail({ activity_id: row.activity_id });
        if (res.data.code == 200) {
          const data = res.data.content.data.info;

          // 处理轮播图数据
          this.bannerFileList = data.activity_banner_arr
            ? data.activity_banner_arr.map(item => ({
              url: item.activity_banner_path
            }))
            : [];

          // 处理活动日期和时间段数据
          const specArr = data.activity_spec_arr || [];
          specArr.forEach(dateItem => {
            if (dateItem.activity_spec_time_arr) {
              dateItem.activity_spec_time_arr.forEach(timeItem => {
                if (timeItem.activity_start_at) {
                  timeItem.activity_start_at = timeItem.activity_start_at.slice(0, 5);
                }
                if (timeItem.activity_end_at) {
                  timeItem.activity_end_at = timeItem.activity_end_at.slice(0, 5);
                }
                timeItem.activity_price = parseFloat(timeItem.activity_price);
              });
            }
          });

          this.form = {
            activity_title: data.activity_title || '',
            activity_category_id: data.activity_category_id || null,
            activity_cover_path: data.activity_cover_path || '',
            activity_banner_arr: data.activity_banner_arr
              ? data.activity_banner_arr.map(item => item.activity_banner_path)
              : [],
            activity_describe: data.activity_describe || '',
            province_id: data.province_id || null,
            city_id: data.city_id || null,
            area_id: data.area_id || null,
            detailed_address: data.detailed_address || '',
            is_home: data.is_home || 0,
            activity_spec_arr: specArr.length > 0
              ? specArr
              : [
                {
                  activity_at: "",
                  activity_spec_time_arr: [
                    {
                      activity_start_at: "",
                      activity_end_at: "",
                      activity_price: 0,
                      activity_people_number: 1
                    }
                  ]
                }
              ]
          };

          // 设置地区选择
          if (data.province_id) {
            this.form.province_id = data.province_id;
            this.cityOptions = await this.fetchDistricts(data.province_id);

            if (data.city_id) {
              this.form.city_id = data.city_id;
              this.areaOptions = await this.fetchDistricts(data.city_id);

              if (data.area_id) {
                this.form.area_id = data.area_id;
              }
            }
          }

          this.updateRegionText();
          this.dialogType = "edit";
          this.dialogVisible = true;
        }
      } catch (error) {
        console.error('获取活动详情失败:', error);
        ElMessage.error('获取活动详情失败');
      }
    },
    async handleEdits(row) {
      try {
        this.activity_id = row.activity_id;
        const res = await api.activityspjifen.getActivityDetail({ activity_id: row.activity_id });
        if (res.data.code == 200) {
          const data = res.data.content.data.info;

          // 处理轮播图数据
          this.bannerFileList = data.activity_banner_arr
            ? data.activity_banner_arr.map(item => ({
              url: item.activity_banner_path
            }))
            : [];

          // 处理活动日期和时间段数据
          const specArr = data.activity_spec_arr || [];
          specArr.forEach(dateItem => {
            if (dateItem.activity_spec_time_arr) {
              dateItem.activity_spec_time_arr.forEach(timeItem => {
                if (timeItem.activity_start_at) {
                  timeItem.activity_start_at = timeItem.activity_start_at.slice(0, 5);
                }
                if (timeItem.activity_end_at) {
                  timeItem.activity_end_at = timeItem.activity_end_at.slice(0, 5);
                }
                timeItem.activity_price = parseFloat(timeItem.activity_price);
              });
            }
          });

          this.form = {
            activity_title: data.activity_title || '',
            activity_category_id: data.activity_category_id || null,
            activity_cover_path: data.activity_cover_path || '',
            activity_banner_arr: data.activity_banner_arr
              ? data.activity_banner_arr.map(item => item.activity_banner_path)
              : [],
            activity_describe: data.activity_describe || '',
            province_id: data.province_id || null,
            city_id: data.city_id || null,
            area_id: data.area_id || null,
            detailed_address: data.detailed_address || '',
            city_name:data.city_name,
            area_name:data.area_name,
            province_name:data.province_name,
            is_home: data.is_home || 0,
            activity_spec_arr: specArr.length > 0
              ? specArr
              : [
                {
                  activity_at: "",
                  activity_spec_time_arr: [
                    {
                      activity_start_at: "",
                      activity_end_at: "",
                      activity_price: 0,
                      activity_people_number: 1
                    }
                  ]
                }
              ]
          };

          // 设置地区选择
          if (data.province_id) {
            this.form.province_id = data.province_id;
            this.cityOptions = await this.fetchDistricts(data.province_id);

            if (data.city_id) {
              this.form.city_id = data.city_id;
              this.areaOptions = await this.fetchDistricts(data.city_id);

              if (data.area_id) {
                this.form.area_id = data.area_id;
              }
            }
          }










const datas = res.data.content.data.activity_pending_data;

          // 处理活动日期和时间段数据
          const specArrs = datas.activity_spec_arr || [];
          specArrs.forEach(dateItem => {
            if (dateItem.activity_spec_time_arr) {
              dateItem.activity_spec_time_arr.forEach(timeItem => {
                if (timeItem.activity_start_at) {
                  timeItem.activity_start_at = timeItem.activity_start_at.slice(0, 5);
                }
                if (timeItem.activity_end_at) {
                  timeItem.activity_end_at = timeItem.activity_end_at.slice(0, 5);
                }
                timeItem.activity_price = parseFloat(timeItem.activity_price);
              });
            }
          });

          this.forms = {
            activity_title: datas.activity_title || '',
            activity_category_id: datas.activity_category_id || null,
            activity_cover_path: datas.activity_cover_path || '',
            activity_banner_arr: datas.activity_banner_arr
              ? data.activity_banner_arr.map(item => item.activity_banner_path)
              : [],
            activity_describe: datas.activity_describe || '',
            province_id: datas.province_id || null,
            city_id: datas.city_id || null,
            area_id: datas.area_id || null,
            detailed_address: datas.detailed_address || '',
            is_home: datas.is_home || 0,
            activity_spec_arr: specArrs.length > 0
              ? specArrs
              : [
                {
                  activity_at: "",
                  activity_spec_time_arr: [
                    {
                      activity_start_at: "",
                      activity_end_at: "",
                      activity_price: 0,
                      activity_people_number: 1
                    }
                  ]
                }
              ]
          };

          // 设置地区选择
          if (datas.province_id) {
            this.form.province_id = datas.province_id;
            this.cityOptions = await this.fetchDistricts(datas.province_id);

            if (datas.city_id) {
              this.form.city_id = data.city_id;
              this.areaOptions = await this.fetchDistricts(datas.city_id);

              if (datas.area_id) {
                this.form.area_id = datas.area_id;
              }
            }
          }





























          this.updateRegionText();
          this.dialogType = "edit";
          this.dialogVisibles = true;
        }
      } catch (error) {
        console.error('获取活动详情失败:', error);
        ElMessage.error('获取活动详情失败');
      }
    },
    handleCloseAddDialog() {
      this.dialogVisible = false;
      this.resetForm();
    },
    handleCloseAddDialogs() {
      this.dialogVisibles = false;
      this.resetForm();
    },
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    },

    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const specArr = this.form.activity_spec_arr.map(dateItem => ({
            activity_at: dateItem.activity_at,
            activity_spec_time_arr: dateItem.activity_spec_time_arr.map(timeItem => ({
              activity_start_at: timeItem.activity_start_at ? `${timeItem.activity_start_at}:00` : '',
              activity_end_at: timeItem.activity_end_at ? `${timeItem.activity_end_at}:00` : '',
              activity_price: timeItem.activity_price.toString(),
              activity_people_number: timeItem.activity_people_number,
              activity_spec_id: timeItem.activity_spec_id
            }))
          }));

          const submitData = {
            activity_title: this.form.activity_title,
            activity_cover_path: this.form.activity_cover_path || '',
            activity_category_id: this.form.activity_category_id,
            activity_describe: this.form.activity_describe,
            province_id: this.form.province_id,
            city_id: this.form.city_id,
            area_id: this.form.area_id,
            detailed_address: this.form.detailed_address,
            is_home: this.form.is_home,
            activity_spec_arr: specArr,
            activity_banner_arr: this.form.activity_banner_arr.map((path, index) => ({
              activity_banner_path: path,
              activity_sort: index + 1
            }))
          };

          const apiMethod = this.dialogType === "edit"
            ? api.activityspjifen.updateActivity
            : api.activityspjifen.createActivity;

          if (this.dialogType === "edit") {
            submitData.activity_id = this.activity_id;
            submitData.activity_spec_id
          }

          apiMethod(submitData).then((res) => {
            if (res?.data.code == 200) {
              ElMessage.success(this.dialogType === "edit" ? "修改成功" : "创建成功");
              this.handleCloseAddDialog();
              this.getTableData();
            } else {
              ElMessage.error(res?.data.message || "操作失败");
            }
          }).catch(error => {
            ElMessage.error("操作失败");
            console.error('操作失败:', error);
          });
        }
      });
    },

    handleAudit(row) {
      this.auditForm = {
        activity_id: row.activity_id,
        activity_title: row.activity_title,
        activity_status: row.activity_status,
        status: 1,
        reject_reason: ''
      };
      this.auditDialogVisible = true;
    },

    submitAudit() {
      if (this.auditForm.status === -1 && !this.auditForm.reject_reason) {
        ElMessage.warning('请填写拒绝原因');
        return;
      }

      const params = {
        activity_id: this.auditForm.activity_id,
        activity_status: this.auditForm.status,
        reject_reason: this.auditForm.status === -1 ? this.auditForm.reject_reason : ''
      };

      api.activityspjifen.auditActivity(params).then(res => {
        if (res.data.code === 200) {
          ElMessage.success('审核成功');
          this.auditDialogVisible = false;
          this.getTableData();
        } else {
          ElMessage.error(res.data.message || '审核失败');
        }
      }).catch(error => {
        ElMessage.error('审核失败');
      });
    }
  }
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-form-item-msg {
  font-size: 12px;
  color: #999;
  line-height: 1.5;
  margin-top: 5px;
}

/* 调整上传组件样式 */
:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
  line-height: 80px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}

.time-slot-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.time-slot-item:last-child {
  margin-bottom: 0;
}

.date-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.time-slot-section {
  margin-top: 15px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.el-divider {
  margin: 10px 0;
}

.el-divider__text {
  font-size: 14px;
  color: #666;
}

.native-select {
  width: 100%;
  height: 32px;
  line-height: 32px;
  padding: 0 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #606266;
  background-color: #fff;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.native-select:hover {
  border-color: #c0c4cc;
}

.native-select:focus {
  outline: none;
  border-color: #409eff;
}

.native-select:disabled {
  background-color: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}
</style>